package cn.edu.hit.kg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;

public class Neo4jConfigurationUtil {
    static Logger logger = LoggerFactory.getLogger(Neo4jConfigurationUtil.class);

    public static String loadConfigure(String classpath) {
        String str = "[]";
        try {
            InputStream inputStream = openFileStream(classpath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            str = reader.lines().reduce((s, s2) -> s + s2).orElse("[]");
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info(str);
        return str;
    }

    public static InputStream openFileStream(String classpath) throws IOException {
        InputStream inputStream;
        File configFile = new File("conf/" + classpath);
        File configFile0 = new File("" + classpath);


        if (configFile0.exists() && configFile0.canRead()) {
            logger.info(configFile0.getAbsolutePath());
            inputStream = new FileInputStream(configFile0);
        } else if (configFile.exists() && configFile.canRead()) {
            logger.info(configFile.getAbsolutePath());
            inputStream = new FileInputStream(configFile);
        } else {
            URL resourceUrl = Neo4jConfigurationUtil.class.getClassLoader().getResource(classpath);
            logger.info(resourceUrl.toString());
            if (resourceUrl == null)
                throw new FileNotFoundException("Cannot find configuration file:" + classpath);
            inputStream = resourceUrl.openStream();
        }
        return inputStream;
    }

    public static void main(String[] args) {
        loadConfigure("configure.json");
    }

}
